package com.superfish.cutieshop.utils;

import android.content.Context;

import com.superfish.cutieshop.BaseApp;
import com.tencent.bugly.crashreport.CrashReport;

public class UID {
    private static final String TAG = UID.class.getSimpleName();

    private static String mId = "DUMMY_ID";
    private static TokenInfo mTokenInfo;

    public static final boolean isUsing(Context context, String uid) {
        return uid.equals(getMyID(context));
    }

    public static synchronized String getMyID(Context context) {
        mId = getTokenInfo(context).id;
        return mId;
    }

    public static synchronized long getServerTime(Context context) {
        return getTokenInfo(context).loginTime;
    }

    public static synchronized void updateToken(Context context, String token) {
        mId = "DUMMY_ID";
        mTokenInfo = null;
        // 传入UID，Bugly注册
        UserInfo.getInstense(context).saveToken(token);
        if (token == null || token.equals("")) {
            return;
        }
        CrashReport.setUserId(getMyID(context));
    }

    public static synchronized String nextToken(Context context) {
        TokenInfo info = getTokenInfo(context);
        if (info == null)
            return "token校验失败";
        String[] tokens = info.makeNext(
                BaseApp.getDeviceId());
        UserInfo.getInstense(context).saveToken(tokens[1]);
        return tokens[0];
    }

    public static synchronized Token$ID nextToken$ID(Context context) {
        return new Token$ID(getMyID(context), nextToken(context));
    }

    public static String encrypt(String s) throws Exception {
        return RsaUtils.encrypt(true, RSA_PUBLIC, s, CHARSET);
    }

    private static TokenInfo getTokenInfo(Context context) {
        return mTokenInfo != null ? mTokenInfo : TokenInfo.fromToken(UserInfo
                .getInstense(context).getToken());
    }


    public static class Token$ID {
        public final String ID;
        public final String token;

        private Token$ID(String id, String token) {
            this.ID = id;
            this.token = token;
        }
    }

    // 安全起见，将改为native
    private static class TokenInfo {
        public final String id;
        public final long loginTime;
        private long increment;
        public final String leftPart;

        private TokenInfo(String id, long loginTime, long increment,
                          String leftPart) {
            this.id = id;
            this.loginTime = loginTime;
            this.increment = increment;
            this.leftPart = leftPart;
        }

        /**
         * 服务端的token，只有前半部分，即：uid+&+time
         **/
        private static TokenInfo fromToken(String token) {
            if (token == null || token.length() == 0)
                return null;
            long no = 0, timeServer;
            String uid$time, decrypt, uid;
            try {
                int index = token.indexOf('$');
                if (index > 0) {
                    if (index < token.length() - 1)
                        no = Long.valueOf(token.substring(index + 1));
                    uid$time = token.substring(0, index);
                } else {
                    uid$time = token;
                }
                decrypt = RsaUtils.decrypt(true, RSA_PUBLIC, uid$time, CHARSET);
                index = decrypt.indexOf("&");
                uid = decrypt.substring(0, index);
                timeServer = Long.valueOf(decrypt.substring(index + 1));
                if (no <= 0)
                    no = timeServer;
                return new TokenInfo(uid, timeServer, no, uid$time);
            } catch (Exception e) {
                return null;
            }
        }

        private String[] makeNext(String deviceId) {
            try {
                increment++;
                return new String[]{
                        RsaUtils.encrypt(true, RSA_PUBLIC,
                                id + "&" + loginTime, CHARSET)
                                + RsaUtils.encrypt(true, RSA_PUBLIC, deviceId
                                + "&" + increment, CHARSET),
                        leftPart + "$" + increment};
            } catch (Exception e) {
                return null;
            }
        }
    }

    private static final String CHARSET = "UTF-8";
    private static final String RSA_PUBLIC = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAKSeIHYSarRl+nZ4iQFZIaCLfB+EjwWvpz5sKUVIfRlTgRItQyWEm6PRos/yT+LWlbnoCMcWUTdvhyxf9d+4WWUCAwEAAQ==";
}
